package br.com.locanet.service.impl;

import javax.persistence.PersistenceException;

import br.com.locanet.bean.impl.Pessoa;
import br.com.locanet.dao.GenericJPADAO;
import br.com.locanet.exception.ExceptionList;
import br.com.locanet.exception.InvalidAttributeException;
import br.com.locanet.service.AbstractEntityService;

public abstract class PessoaService<ENTITY extends Pessoa, ENTITYDAO extends GenericJPADAO<ENTITY>> extends AbstractEntityService<ENTITY, ENTITYDAO>{
	@Override
	public void doValidateRequiredFields(ENTITY entity) 
			throws ExceptionList {
		ExceptionList fieldsInvalidos = new ExceptionList();
		
		if (entity.getNome() == null || entity.getNome().isEmpty())
			fieldsInvalidos.add(new InvalidAttributeException(( "nomeNaoInformado")));
		
		if (entity.getLogin() == null || entity.getLogin().isEmpty())
			fieldsInvalidos.add(new InvalidAttributeException( "loginNaoInformado"));
		else if (entity.getLogin().length()<6 || entity.getLogin().length()>20)
			fieldsInvalidos.add(new InvalidAttributeException(( "loginForaDeTamanho")));
		
		if (entity.getSenha() == null || entity.getSenha().isEmpty())
			fieldsInvalidos.add(new InvalidAttributeException( "senhaNaoInformada"));
		else if (entity.getSenha().length()<6 || entity.getSenha().length()>20)
			fieldsInvalidos.add(new InvalidAttributeException(( "senhaForaDeTamanho")));
		
		validaRepeticaoLogin(entity,fieldsInvalidos);

		if (!fieldsInvalidos.getListaErros().isEmpty()) throw fieldsInvalidos;
	}
	
	public void doValidateBusinessRules(ENTITY entity) 
			throws ExceptionList, PersistenceException, ClassNotFoundException {
	}

	public void doValidateSenha(Pessoa entity, String confSenha)
	        throws InvalidAttributeException {
      if (entity.getSenha()==null||!entity.getSenha().equals(confSenha))
	       throw new InvalidAttributeException("senhaDiferenteConfirmacao");
    }
	
	protected void validaRepeticaoLogin(ENTITY entity,ExceptionList exceptionList) {
		try {
			for (ENTITY p : getEntityDAO().findAll()){
				if (p.getLogin().equalsIgnoreCase(entity.getLogin()) && !p.getId().equals(entity.getId())){
					exceptionList.add(new InvalidAttributeException("loginJaCadastrado"));
					break;
				}
			}
		} catch (Exception e) {
			exceptionList.add(e);
		}
	}
}

